package com.wzc.hc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzc.hc.entity.po.Business;
import com.wzc.hc.entity.po.Contact;
import com.wzc.hc.entity.resp.Result;
import com.wzc.hc.entity.tool.BeanConverter;
import com.wzc.hc.entity.vo.BusinessVo;
import com.wzc.hc.entity.vo.ContactVo;
import com.wzc.hc.service.BusinessService;
import com.wzc.hc.service.ContactService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/*
    @author: m1825
    @date: 2025/3/5 18:12
*/
@Tag(name = "业委会")
@RestController
@RequestMapping("/business")
public class BusinessController {
    @Resource
    private BusinessService businessService;
    @Resource
    private ContactService contactService;

    @Operation(summary = "新增")
    @PostMapping("/add")
    public Result<Object> add(@RequestBody BusinessVo businessVo) {
        try {
            Business business = BeanConverter.convertVoToPo(businessVo, Business.class);
            List<Contact> contacts = new ArrayList<>();
            businessService.save(business);
            businessVo.getContactVos().forEach(contactVo -> {
                Contact contact = BeanConverter.convertVoToPo(contactVo, Contact.class);
                contact.setBusinessId(business.getId());
                contacts.add(contact);
            });
            contactService.saveBatch(contacts);
            return Result.ok();
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "分页查看")
    @GetMapping("/page")
    public Result<Page<BusinessVo>> page(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        try {
            Page<Business> page = new Page<>(pageNum, pageSize);
            Page<Business> businessPage = businessService.page(page);
            Page<BusinessVo> businessVoPage = getBusinessVoPage(pageNum, pageSize, businessPage);
            return Result.ok(businessVoPage);
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "查询")
    @PostMapping("/select")
    public Result<Page<BusinessVo>> select(@RequestBody BusinessVo businessVo,
                                           @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        try {
            Business business = BeanConverter.convertVoToPo(businessVo, Business.class);
            Page<Business> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Business> businessQueryWrapper = new QueryWrapper<>();
            if (business.getName() != null)
                businessQueryWrapper.like("name", business.getName());
            if (business.getPhone() != null)
                businessQueryWrapper.like("phone", business.getPhone());
            if (business.getState() != null)
                businessQueryWrapper.eq("state", business.getState());
            Page<Business> businessPage = businessService.page(page, businessQueryWrapper);
            Page<BusinessVo> businessVoPage = getBusinessVoPage(pageNum, pageSize, businessPage);
            return Result.ok(businessVoPage);
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @NotNull
    private static Page<BusinessVo> getBusinessVoPage(int pageNum, int pageSize, Page<Business> businessPage) {
        List<BusinessVo> businessVos = businessPage.getRecords().stream()
                .map(business -> BeanConverter.convertPoToVo(business, BusinessVo.class))
                .toList();
        Page<BusinessVo> businessVoPage = new Page<>(pageNum, pageSize, businessPage.getTotal());
        businessVoPage.setRecords(businessVos);
        return businessVoPage;
    }

    @Operation(summary = "单个详情")
    @GetMapping("/getOne")
    public Result<BusinessVo> getOne(@RequestParam(value = "BusinessId") String id) {
        try {
            Business business = businessService.getById(id);
            QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
            contactQueryWrapper.eq("business_id", id);
            List<Contact> contacts = contactService.list(contactQueryWrapper);
            List<ContactVo> contactVos = contacts.stream().map(contact -> BeanConverter.convertPoToVo(contact, ContactVo.class)).toList();
            BusinessVo businessVo = BeanConverter.convertPoToVo(business, BusinessVo.class);
            businessVo.setContactVos(contactVos);
            return Result.ok(businessVo);
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "删除")
    @DeleteMapping("/deleteBusiness")
    public Result<Object> deleteBusiness(@RequestParam(value = "Id") String id) {
        try {
            QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
            contactQueryWrapper.eq("business_id", id);
            contactService.remove(contactQueryWrapper);
            businessService.removeById(id);
            return Result.ok();
        } catch (Exception e) {
            return Result.fail();
        }
    }

    @Operation(summary = "更新")
    @PutMapping("/update")
    public Result<Object> update(@RequestBody BusinessVo businessVo) {
        try {
            List<String> list = businessVo.getContactVos().stream().map(contactVo -> {
                Contact contact = BeanConverter.convertVoToPo(contactVo, Contact.class);
                contact.setBusinessId(businessVo.getId());
                if (contact.getId() == null)
                    contactService.save(contact);
                else
                    contactService.updateById(contact);
                return contact.getId();
            }).toList();
            QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
            contactQueryWrapper.eq("business_id", businessVo.getId());
            List<Contact> contacts = contactService.list(contactQueryWrapper);
            contacts.forEach(contact -> {
                if (!list.contains(contact.getId()))
                    contactService.removeById(contact);
            });
            businessService.updateById(BeanConverter.convertVoToPo(businessVo, Business.class));
            return Result.ok();
        } catch (Exception e) {
            return Result.fail();
        }
    }
}